﻿using Newtonsoft.Json;
using Robin.Logging;
using Robin.Specifications;
using Robin.Web.Mvc.Controllers;
using Smart.Project.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;

namespace Smart.Project.Web.Controllers
{
    public class EventController : RobinController
    {
        IEventRepository _resp;
        ITagRepository _Tagresp;
        IProjectinfoRepository _Proresp;
        public EventController(IEventRepository resp, ITagRepository Tagresp, IProjectinfoRepository Proresp)
        {
            _resp = resp;
            _Tagresp = Tagresp;
            _Proresp = Proresp;
        }
        // GET: Event
        public ActionResult Index()
        {
            return View();
        }
        #region 获取下拉信息
        /// <summary>
        /// 获取下拉信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string GetAllTagSel()
        {
             string PROJECTID = Request["PROJECTID"];
            string result = string.Empty;
            var list = _Tagresp.GetAllList(a=>a.PROJECT.Id==PROJECTID);
            List<SelSummaryModel> formlist = new List<SelSummaryModel>();
            foreach (var Sel in list)
            {
                SelSummaryModel m = new SelSummaryModel();
                m.name = Sel.NAME;
                m.value = Sel.Id;
                formlist.Add(m);
            }
            result = JsonConvert.SerializeObject(formlist);
            return result;
        }
        #endregion
        //Create
        public ActionResult Create()
        {
            MEvent model = new MEvent() { Id = System.Guid.NewGuid().ToString()};
            return View(model);
        }

        [HttpPost]
        public string Create(MEvent model)
        {
            string result = "false";
            var dateNow = DateTime.Now;
            try
            {
                //model.CREATETIME = decimal.Parse(dateNow.ToString("yyyyMMddHHmmss"));
                //model.UPDATETIME = decimal.Parse(dateNow.ToString("yyyyMMddHHmmss"));
                var emodel = _resp.Count(a => a.EVENTNAME == model.EVENTNAME);
                if (emodel > 0)
                {
                    result = "事件名称已存在！";
                }
                else
                {
                    var tagmodel = _Tagresp.Count(a => a.Id == model.TAG.Id);
                    if (tagmodel == 0)
                    {
                        MTag mtag = new MTag() { Id = System.Guid.NewGuid().ToString() };
                        mtag.NAME = model.TAG.Id;
                        MProjectinfo mPro = _Proresp.Get(model.PROJECTID.Id);
                        mtag.PROJECT = mPro;
                        model.TAG.Id = mtag.Id;
                        _Tagresp.Insert(mtag);
                        model.TAG = mtag;
                    }
                    else
                    { 
                    model.TAG = model.TAG.Id != null ? _Tagresp.Get(model.TAG.Id) : null;
                    }
                    //model.PROJECTID = model.PROJECTID.Id != null ? _Proresp.Get(model.PROJECTID.Id) : null;
                    _resp.Insert(model);
                    result = "true";
                }
            }
            catch (Exception ex)
            {
                result = "false";
                LogManager.Logger.Error("EventController Create", ex);
            }
            return result;
        }

        //Updata
        public ActionResult Update(string Id)
        {
            MEvent model = _resp.Get(Id);
            return View(model);
        }

        [HttpPost]
        public string Update(MEvent model)
        {
            string result = "false";
            var dateNow = DateTime.Now;
            try
            {
                var emodel = _resp.Count(a => a.EVENTNAME == model.EVENTNAME && a.Id != model.Id);
                if (emodel >0)
                {
                    result = "事件名称已存在！";
                }
                else
                {
                    //model.UPDATETIME = decimal.Parse(dateNow.ToString("yyyyMMddHHmmss"));
                    var tagmodel = _Tagresp.Count(a => a.Id == model.TAG.Id);
                    if (tagmodel == 0)
                    {
                        MTag mtag = new MTag() { Id = System.Guid.NewGuid().ToString() };
                        mtag.NAME = model.TAG.Id;
                        MProjectinfo mPro = _Proresp.Get(model.PROJECTID.Id);
                        mtag.PROJECT = mPro;
                        model.TAG.Id = mtag.Id;
                        _Tagresp.Insert(mtag);
                    }
                    model.TAG = model.TAG.Id != null ? _Tagresp.Get(model.TAG.Id) : null;
                    model.PROJECTID = model.PROJECTID.Id != null ? _Proresp.Get(model.PROJECTID.Id) : null;
                    _resp.Update(model);
                    result = "true";
                }
            }
            catch (Exception ex)
            {
                result = "false";
                LogManager.Logger.Error("EventController Update", ex);
            }
            return result;
        }

        //Detail
        public ActionResult Detail(string Id)
        {
            MEvent model = _resp.Get(Id);
            return View(model);
        }

        public string Delete(string id)
        {
            string result = "false";
            try
            {
                _resp.Delete(id);
                result = "true";
            }
            catch (Exception ex)
            {
                result = "false";
                LogManager.Logger.Error("EventController Delete", ex);
            }
            return result;
        }

        public string GetEventList()
        {
            string result = string.Empty;
            //项目ID
            string PROJECTID = Request["PROJECTID"];
            string Tagid = Request["Tagid"];
            decimal BEGINTYPE = Request["BEGINTYPE"]==""? decimal.MinValue: decimal.Parse(Request["BEGINTYPE"].Replace("-","").Replace(" ", "").Replace(":", ""));
            decimal ENDTYPE = Request["ENDTYPE"] == "" ?decimal.MaxValue:decimal.Parse(Request["ENDTYPE"].Replace("-", "").Replace(" ", "").Replace(":", ""));
            string echo = Request["sEcho"];
            string iDisplayStart = Request["iDisplayStart"];
            string iDisplayLength = Request["iDisplayLength"];
            int count = 0;
            int startIndex = 0, pagesize = 7;
            int.TryParse(iDisplayStart, out startIndex);
            int.TryParse(iDisplayLength, out pagesize);
            Expression<Func<MEvent, bool>> where = item => true;
            FormatedList<List<MEvent>> formlist = new FormatedList<List<MEvent>>();
            where = where.And(item => item.PROJECTID.Id.Contains(PROJECTID) && item.EVENTTIME > BEGINTYPE && item.EVENTTIME < ENDTYPE && Tagid==""?true:item.TAG.Id == Tagid);
            var list = _resp.GetList(where, obj => obj.Asc(item => item.EVENTTIME), startIndex, pagesize).ToList();
            try
            {
                for (int i=0;i<list.Count;i++)
                {
                    list[i].NUMBER = i+1;
                }
                count = _resp.GetAllList(where).Count();
                formlist.sEcho = int.Parse(echo);
                formlist.iTotalRecords = count;
                formlist.iTotalDisplayRecords = count;
                formlist.aaData = list;
                result = JsonConvert.SerializeObject(formlist);
            }
            catch (Exception ex)
            {
                LogManager.Logger.Error("EventController GetList", ex);
            }
            return result;
        }
        public string GetEventTimeList()
        {
            string result = string.Empty;
            string PROJECTID = Request["PROJECTID"];
            string Tagid = Request["Tagid"];
            decimal BEGINTYPE = Request["BEGINTYPE"] == "" ? decimal.MinValue : decimal.Parse(Request["BEGINTYPE"].Replace("-", "").Replace(" ", "").Replace(":", ""));
            decimal ENDTYPE = Request["ENDTYPE"] == "" ? decimal.MaxValue : decimal.Parse(Request["ENDTYPE"].Replace("-", "").Replace(" ", "").Replace(":", ""));
            Expression<Func<MEvent, bool>> where = item => true;
            where = where.And(item => item.PROJECTID.Id.Contains(PROJECTID) && item.EVENTTIME > BEGINTYPE && item.EVENTTIME < ENDTYPE && Tagid == "" ? true : item.TAG.Id == Tagid);
            //, obj => obj.Asc(item => item.Id)
            List<MEvent> list = _resp.GetAll().Where(where).OrderBy(a=>a.EVENTTIME).ToList();
            try
            {
                for (int i = 0; i < list.Count; i++)
                {
                    list[i].NUMBER = i + 1;
                }
                result = JsonConvert.SerializeObject(list);
            }
            catch (Exception ex)
            {
                LogManager.Logger.Error("EventController GetList", ex);
            }
            return result;
        }
    }
}